package code.class1;

import cn.hutool.core.util.ArrayUtil;

/**
 * https://leetcode.cn/problems/reverse-only-letters/description/
 * 仅仅反转字符
 * <p>
 * 双指针
 */
public class Code09_ReverseOnlyLetters {
    public static void main(String[] args) {
//        String str = "ab-cd"; //dc-ba
//        String str = "a-bC-dEf-ghIj"; //j-Ih-gfE-dCba
        String str = "Test1ng-Leet=code-Q!"; //Qedo1ct-eeLg=ntse-T!
        String res = reverseOnlyLetters(str);
        System.out.println(ArrayUtil.toString(res));
    }

    public static String reverseOnlyLetters(String str) {
        char[] arr = str.toCharArray();
        int p1 = 0, p2 = arr.length - 1;
        while (p1 < p2) {
            if (!isCharactor(arr[p1])) { // 当 p1 不为字符时，p1++
                p1++;
            } else if (!isCharactor(arr[p2])) {
                p2--;
            } else {
                swap(arr, p1++, p2--); // 只交换字符
            }
        }
        return new String(arr);
    }

    // 判断是否为字符
    public static boolean isCharactor(char c) {
        return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
    }

    public static void swap(char[] arr, int x, int y) {
        char t = arr[x];
        arr[x] = arr[y];
        arr[y] = t;
    }
}
